﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using System.Windows.Media.Imaging;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class Amici : PhoneApplicationPage
    {
        private static string key = "user";

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private string idfriend;
        private string friendname;

        private Style containerStyle = Application.Current.Resources["MyCardCanvas"] as Style;
        private Style borderStyle = Application.Current.Resources["MyCardCardBorder"] as Style;
        private Style nameTextStyle = Application.Current.Resources["MyCardTextName"] as Style;
        private Style matchesTextStyle = Application.Current.Resources["friendsG"] as Style;
        private Style removeStyle = Application.Current.Resources["Remove"] as Style;

        public Amici()
        {
            InitializeComponent();
        }

        private void ContainerList_Loaded(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/friends.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackFriends), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            friendname = FriendBox.Text.ToLower();

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getFriendName.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetFriendName), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void removeButton_Tap(object sender, EventArgs e)
        {
            Button clicked = sender as Button;
            idfriend = clicked.Tag as string;

            ContainerList.Items.Remove(clicked.Parent);

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/removeFriend.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackRemoveFriend), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void GetRequestStreamCallbackFriends(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackFriends), myRequest);
        }//GetRequestStreamCallbackFriends

        private void GetResponsetStreamCallbackFriends(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingFriends(result));
            }
        }//GetResponsetStreamCallbackFriends

        private void ParsingFriends(string result)
        {
            //controllo result
            if (result != "")//ho preferiti
            {
                //parsing e creo lista
                string[] ris = majorSplit(result);
                foreach (string record in ris)
                {
                    string[] dati = minorSplit(record);
                    string id = dati[0];
                    string name = dati[1];
                    string imageURL = dati[2];
                    string won = dati[3];
                    string lost = dati[4];

                    Canvas container = new Canvas();
                    container.Style = containerStyle;
                    var containerback = new ImageBrush();
                    Uri imageuricontainer = new Uri("img/buttonbg.png", UriKind.Relative);
                    containerback.ImageSource = new BitmapImage(imageuricontainer);
                    container.Background = containerback;

                    Border bord = new Border();
                    bord.Style = borderStyle;
                    var bordback = new ImageBrush();
                    Uri imageuribord = new Uri(imageURL, UriKind.Absolute);
                    bordback.ImageSource = new BitmapImage(imageuribord);
                    bord.Background = bordback;

                    TextBlock nameText = new TextBlock();
                    nameText.Style = nameTextStyle;
                    nameText.Foreground = new SolidColorBrush(Colors.Black);
                    nameText.Text = name;

                    TextBlock matchesText = new TextBlock();
                    matchesText.Style = matchesTextStyle;
                    matchesText.Foreground = new SolidColorBrush(Colors.Black);
                    matchesText.Text = "W/L\n" + won + "/" + lost;

                    Button removeButton = new Button();
                    removeButton.Style = removeStyle;
                    removeButton.Content = "Remove Friend";
                    removeButton.Background = new SolidColorBrush(Color.FromArgb(255, 135, 0, 0));
                    Canvas.SetLeft(removeButton, 287);
                    Canvas.SetTop(removeButton, 118);
                    removeButton.Width = 150;
                    removeButton.Name = id;
                    removeButton.Tag = id;
                    removeButton.Tap += new EventHandler<GestureEventArgs>(removeButton_Tap);

                    container.Children.Add(bord);
                    container.Children.Add(nameText);
                    container.Children.Add(matchesText);
                    container.Children.Add(removeButton);

                    ContainerList.Items.Add(container);
                }
            }
        }//ParsingFriends

        private void GetRequestStreamCallbackGetFriendName(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&FriendName=" + friendname;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGetFriendName), myRequest);
        }//GetRequestStreamCallbackAddFriend

        private void GetResponsetStreamCallbackGetFriendName(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGetFriendName(result));
            }
        }//GetResponsetStreamCallbackAddFriend

        private void ParsingGetFriendName(string result)
        {
            if (result == "")
            {
                MessageBox.Show("The user " + friendname + " doesn't exist");
            }
            else
            {
                idfriend = result;

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/addFriend.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackAddFriend), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
            
        }//ParsingGetFriendName

        private void GetRequestStreamCallbackAddFriend(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + io.getId().ToString() + "&IdFriend=" + idfriend;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackAddFriend), myRequest);
        }//GetRequestStreamCallbackAddFriend

        private void GetResponsetStreamCallbackAddFriend(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingAddFriend(result));
            }
        }//GetResponsetStreamCallbackAddFriend

        private void ParsingAddFriend(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                MessageBox.Show("You and " + FriendBox.Text + " are now friends!");
                //refresh
                RoutedEventArgs eve = new RoutedEventArgs();
                ContainerList_Loaded(this, eve);
            }
        }//ParsingAddFriend

        private void GetRequestStreamCallbackRemoveFriend(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + io.getId().ToString() + "&IdFriend=" + idfriend;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackRemoveFriend), myRequest);
        }//GetRequestStreamCallbackRemoveFriend

        private void GetResponsetStreamCallbackRemoveFriend(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingRemoveFriend(result));
            }
        }//GetResponsetStreamCallbackRemoveFriend

        private void ParsingRemoveFriend(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                MessageBox.Show("Friend removed!");
                //refresh
                RoutedEventArgs eve = new RoutedEventArgs();
                ContainerList_Loaded(this, eve);
            }
        }//ParsingRemoveFriend

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}